package com.xyj.netty.chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author GuXiaoYao
 * @version 1.0.0
 * @since 2021/9/7
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {


    //GlobalEventExecutor.INSTANCE 是全局的事件执行器，是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 通知各个客户端
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"下线了, +下线时间"+sdf.format(new Date()) +"\n");
        System.out.println("[客户端]"+channel.remoteAddress()+"下线了, +上线时间"+sdf.format(new Date()) +"\n");
    }

    /**
     * 上线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 通知各个客户端
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress()+"上线了, +上线时间"+sdf.format(new Date()) +"\n");
        // 将当前客户端加入channel中
        channelGroup.add(channel);
        System.out.println("[客户端]"+channel.remoteAddress()+"上线了, +上线时间"+sdf.format(new Date()) +"\n");
    }

    /**
     * 读取消息
     * @param channelHandlerContext
     * @param s
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        Channel channel = channelHandlerContext.channel();
        // 一个客户端发消息，所有客户端都能看到，不过展示不同
        channelGroup.forEach(x->{

            if (channel.equals(x)){
                // 对于当前客户端，发送内容不一样
                x.writeAndFlush(sdf.format(new Date())+"[我自己发送了]："+s+"\n");
            }else {
                x.writeAndFlush(sdf.format(new Date())+"["+channel.remoteAddress()+"发送了]："+s+"\n");
            }
        });
        System.out.println(sdf.format(new Date())+"[客户端"+channel.remoteAddress()+"发送了]："+s+"\n");
    }

    /**
     * 关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}
